// import { LoginPage } from './../pages/login/login';
import { NoticeService } from './notice-service';
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import { AlertController, LoadingController, ToastController, ActionSheetController } from 'ionic-angular';

@Injectable()
export class Api {



	private loading;
	constructor(
		private http: Http,
		// private navCtrl: NavController,
		private toastCtrl: ToastController,
		private alertCtrl: AlertController,
		private actionSheetCtrl: ActionSheetController,
		private loadingCtrl: LoadingController,
		private noticeService: NoticeService
	) {

	}	
	
	public apiUrl = 'http://demo.ilaizhan.com:8082/';

	// 弹出登陆确认框
	jumpLogin() {
		this.noticeService.presentConfirm("", "您的设备在其他地方登录了,\n请重新登录", data => {

		});
	}

	// 获取用户信息
	getUserinfo(key = null) {
		let user = eval('(' + this.getLocalStorage("User") + ')');
		if (key) {
			let str = "";
			if (user) {
				str = user[key];
			}
			return str;
		} else {
			return user;
		}
	}
	/**
	 * 获取链接地址
	 * @param key 
	 */
	getUserUrl(key) {
		let url = eval('(' + this.getLocalStorage("url") + ')');
		return url[key];
	}

	public postBody(url: string, paramObj: any) {

	
		let _postUrl = this.apiUrl + url;
		let hearOptions = {
			"Content-Type": "application/json",
			"DeviceKey": this.getLocalStorage("DeviceKey"),
			"DeviceType": this.getLocalStorage("DeviceType"),
			"AppVersion": this.getLocalStorage("AppVersion"),
			"Ticket": this.getLocalStorage("Ticket")
		}
		let headers = new Headers(hearOptions);
		return this.http
			.post(_postUrl, paramObj, new RequestOptions({ headers: headers }))
			.toPromise()
			.then((res) => this.handleSuccess(res))
			.catch((error) => this.handleError(error));
	}

	/**
 * 请求成功
 * @param result 
 */
	private handleSuccess(result) {
		console.log(result);
		result = result.json()
		if (result.Code == -1) {
			this.jumpLogin();
			return;
		} else if (result.Code == 0) {
			return result;
		}
		return result;
	}
	/**
 * 请求失败
 * @param error 
 */
	private handleError(error: Response | any) {
		console.log(error);
		let msg = '请求失败';
		if (error.status == 0) {
			msg = '请求地址错误';
		}
		if (error.status == 400) {
			msg = '请求无效';
		}
		if (error.status == 404) {
			msg = '请求资源不存在';
		}
		this.noticeService.showNoticeByToast(2, msg);
		// return { success: false, msg: msg };
	}

	/**
 * 展示等待弹窗
 * @param waitMsg 
 */
	showWait(waitMsg = '请稍候...') {
		this.loading = this.loadingCtrl.create({
			content: waitMsg
		});
		this.loading.present();
		return this.loading;
	}
	/**
 * 隐藏等待弹窗
 */
	hideWait() {
		this.loading && this.loading.dismiss();
	}

	/**
 * Alert  提示信息
 * @param msg 
 * @param showTimes 
 * @param cb 
 */
	showTip(msg, showTimes = 150500, cb = null) {
		let _toastMsg = '';
		if (typeof msg === 'string') {
			_toastMsg = msg;
		} else if (typeof msg === 'object') {
			_toastMsg = msg.message || '';
		}
		if (typeof _toastMsg === 'string' && _toastMsg !== '') {
			let alertObj = this.alertCtrl.create({
				subTitle: msg,
				buttons: [
					{
						text: '确认',
						handler: () => {
							cb && cb();
						}
					}
				]
			});
			this.toastCtrl.create({
				message: _toastMsg,
				position: 'bottom',
				duration: showTimes
			});
			alertObj.present();
		}
	}
	/**
	 * 
	 */
	isMobileWeb() {
		return true;
	}

	/**
 * 写入LocalStorage
 * @param key 
 * @param value 
 */
	writeLocalStorage(key: string, value: any) {
		if (value) {
			value = JSON.stringify(value);
		}
		localStorage.setItem(key, value);
	}
	/**
	 * 读取LocalStorage
	 * @param key 
	 */
	getLocalStorage(key: string) {

		let value = localStorage.getItem(key);
		if (value && value != undefined && value != null) {
			return value;
		}
		return null;
	}

	del
	/**
	 * 底部上弹菜单
	 * @param title 
	 * @param btnArray 
	 */
	presentActionSheet(title: string, btnArray: Array<Object>) {
		btnArray.push({
			text: "取消",
			role: "cancel",
		});
		let actionSheet = this.actionSheetCtrl.create({
			title: title,
			buttons: btnArray
		});
		actionSheet.present();
	}

	showNoticeByToast(code: Number, msg: string) {
		this.noticeService.showNoticeByToast(code, msg);
	}



	dataVer() {

	}
	getImgList() {
		this.postBody('V1/GetUrl', {})
			.then((data) => {
				let obj = data.Data;
				localStorage.setItem('url', JSON.stringify(obj));
			});
		this.postBody("V1/GetStarImg", {})
			.then((data) => {
				if (data.Code == 0) {
					let obj = data.Data;
				let	imgList=[];
					imgList.push(obj.Img1);
					imgList.push(obj.Img2);
					imgList.push(obj.Img3);
					localStorage.setItem("imgList", JSON.stringify(imgList));
				}
			})
	}
}
